package com.demo.key.server

import com.demo.key.listeners.IStateChangedListener
import com.demo.key.pa.Abs0822Page
import com.github.shadowsocks.Core
import com.github.shadowsocks.aidl.IShadowsocksService
import com.github.shadowsocks.aidl.ShadowsocksConnection
import com.github.shadowsocks.bg.BaseService
import com.github.shadowsocks.preference.DataStore
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

object ConnectServer0822Manager:ShadowsocksConnection.Callback {
    private var context:Abs0822Page?=null
    var current=ServerInfo0822Manager.createFastServer()
    var last=ServerInfo0822Manager.createFastServer()
    private var state=BaseService.State.Idle
    private val sc=ShadowsocksConnection(true)
    private var iStateChangedListener: IStateChangedListener?=null

    fun setIStateChangedListener(iStateChangedListener:IStateChangedListener){
        this.iStateChangedListener=iStateChangedListener
    }

    fun initShadowsocksConnection(context:Abs0822Page){
        this.context=context
        sc.connect(context,this)
    }

    fun connect(){
        state=BaseService.State.Connecting
        GlobalScope.launch {
            if (ServerInfo0822Manager.checkServerIsFast(current)){
                val f = ServerInfo0822Manager.getSuperFastServer()
                if (null!=f){
                    DataStore.profileId = ServerInfo0822Manager.getServerInfoId(f)
                    Core.startService()
                }
            }else{
                DataStore.profileId = ServerInfo0822Manager.getServerInfoId(current)
                Core.startService()
            }
        }
    }

    fun disconnect(){
        state=BaseService.State.Stopping
        GlobalScope.launch {
            Core.stopService()
        }
    }


    fun connected()= BaseService.State.Connected==state

    private fun stopped()= BaseService.State.Stopped==state

    fun actionComplete(isConnect:Boolean)=if (isConnect) connected() else stopped()

    override fun stateChanged(state: BaseService.State, profileName: String?, msg: String?) {
        this.state=state
        if (stopped()){
            ConnectTime0822Manager.stopCountTime()
            iStateChangedListener?.stateChanged(state)
        }
        if (connected()){
            last= current
            ConnectTime0822Manager.startCountTime()
        }
    }

    override fun onServiceConnected(service: IShadowsocksService) {
        val state = BaseService.State.values()[service.state]
        this.state=state
        if (connected()){
            last= current
            iStateChangedListener?.stateChanged(state)
        }
    }

    override fun onBinderDied() {
        context?.run {
            sc.disconnect(this)
        }
    }

    fun onDestroy(){
        onBinderDied()
        context=null
    }

}